package com.kits.store

import android.content.ContentProvider
import android.content.ContentValues
import android.content.Intent
import android.content.UriMatcher
import android.database.AbstractCursor
import android.database.CursorWindow
import android.net.Uri
import android.os.Binder
import android.provider.Telephony.TextBasedSmsColumns.PERSON
import com.kits.store.db.DbFactory


/**
 * 通过 FileExProvider 给应用赋权限
 */
class FileExProvider : ContentProvider(){


    companion object{
        const val TAG = "DbProvider"
        const val AUTHORITY ="com.kits.store.FileExProvider"
        const val MATCH_FILE_CODE = 100
        private var NOTIFY_URI = Uri.parse("content://$AUTHORITY/file")
        private val mUriMatcher : UriMatcher = UriMatcher(UriMatcher.NO_MATCH)

    }


    override fun insert(uri: Uri, values: ContentValues?): Uri? {
        TODO("Not yet implemented")
    }

    override fun query(
        uri: Uri,
        projection: Array<out String>?,
        selection: String?,
        selectionArgs: Array<out String>?,
        sortOrder: String?
    ): android.database.Cursor? {
        if (mUriMatcher.match(uri)==MATCH_FILE_CODE){
            println("${mUriMatcher.match(uri)}")
        }
        val callApp = context?.packageManager?.getNameForUid(Binder.getCallingUid())
        println("调用者== $callApp")
        // 这里是为了简单这么写，正式使用需要对sql 进行拼接
        // 对Uri 进行权限赋值
        // val cursor = DbFactory.getInstance().writableDatabase?.rawQuery("select * from FILE_BEAN",null)

        val cursor = DbFactory.getInstance().writableDatabase?.rawQuery("select * from FILE_BEAN",null)
        if (cursor != null && cursor.count > 0){
            cursor.moveToFirst()
            do {
                permission(callApp,cursor.getString(cursor.getColumnIndex("URI")))
            }while (cursor.moveToNext())
        }
        return cursor

    }

    override fun onCreate(): Boolean {
        mUriMatcher.addURI(AUTHORITY, "file", MATCH_FILE_CODE)
        return true
    }

    override fun update(
        uri: Uri,
        values: ContentValues?,
        selection: String?,
        selectionArgs: Array<out String>?
    ): Int {
        throw UnsupportedOperationException("No external inserts")
    }

    override fun delete(uri: Uri, selection: String?, selectionArgs: Array<out String>?): Int {
        TODO("Not yet implemented")
        throw UnsupportedOperationException("No external inserts")
    }

    /**
     * 作用在于隐式启动
     */
    override fun getType(uri: Uri): String? {
        TODO("Not yet implemented")
    }
    /**
     * 赋予权限
     */
    private fun permission(packageName:String?,uri:String){
        println("packageName == $packageName;uri == $uri")
        val fileUri = Uri.parse(uri)
        context?.grantUriPermission(packageName, fileUri, Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
    }
}